﻿/**
 * 表格的删除功能。
 */
Ext.define('Happy.grid.action.Delete', {
    extend: 'Happy.Action',
    alias: 'action.grid-delete',
    requires: [
        'Happy.Msg',
        'Happy.Ajax'
    ],

    /**
     * @inheritdoc
     */
    defaultConfig: {
        itemId: 'delete',
        iconCls: 'delete-button',
        text: '删除',
        disabled: true,
        autoEnableAndDisable: true,
        remoteDelete: true,
        gridSelector: 'grid'
    },

    /**
     * @inheritdoc
     */
    onClickHandler: function (button) {
        var me = this;

        var grid = me.up(button, me.initialConfig.gridSelector);
        var records = grid.getSelection();

        if (records.length == 0) {
            return;
        }

        Happy.Msg.confirmDelete(function () {
            if (me.initialConfig.remoteDelete === true) {
                me.deleteRecords(records);
            }
            else {
                grid.getStore().remove(records);
            }
        });
    },

    /**
     * 批量删除记录。
     *
     * 思考一个问题，批量删除的记录需要在一个事务中吗？多数场景是不用的，因此这里会发送多个请求，当然
     * 这种思路还是有待改进，比如：可以考虑使用分批发送的模式。
     * 
     * @private
     * @param {Array} records
     */
    deleteRecords: function (records) {
        var me = this;

        if (records.length == 0) {
            Happy.Msg.showDeleteSuccess();
            return;
        }

        Happy.Ajax.destroy(records.shift(), {
            success: function (record) {

                me.deleteRecords(records);
            },
            failure: function (record, operation) {
                Happy.Msg.showDeleteFailure(operation.error);
            }
        });
    }
});